package com.blogspot.ostas.oracle.aq.spring.test;

import oracle.jms.AQjmsOracleDebug;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.jms.listener.DefaultMessageListenerContainer;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TextMessage;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;

import static org.junit.Assert.assertNotNull;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:applicationContext-oracle.xml"})
public class OracleAqListenerTestCase {
	static Logger logger = Logger.getLogger(OracleAqListenerTestCase.class.getName());
	@Autowired
	private DefaultMessageListenerContainer jmsContainer;
    @Autowired
    private JmsTemplate jmsTemplateOracle;

    @Test
    public void sendMessage()
    {
        assertNotNull(jmsTemplateOracle);
        logger.debug("Sending message ... ");
        jmsTemplateOracle.send(new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                TextMessage message = session.createTextMessage();
                message.setText("Hello from spring jms to oracle !!!");
                return message;
            }
        });
        logger.debug("Sending done!");
    }

	@Test
    public void testJmsAqSendTest()
    {
        String logFileName = "whatever";
        int traceLevel = 5;  // valid values are 1 (lowest) to 5 (highest)
        File file = new File(logFileName);
        OutputStream outputStream = null;
                try {
                    outputStream = new FileOutputStream(file);
                } catch (FileNotFoundException e) {
                    logger.error(e);
                }
        AQjmsOracleDebug.setLogStream(outputStream);
        AQjmsOracleDebug.setTraceLevel(traceLevel);
        AQjmsOracleDebug.setDebug(true);
        
        jmsContainer.start();
        jmsContainer.initialize();
        sendMessage();
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            logger.error(e);
        }
        logger.debug("Sending done!");

        jmsContainer.stop();
    }
}
 